//
//  AppDelegate.m
//  Inforcollection
//
//  Created by macbook on 15/11/30.
//  Copyright © 2015年 oceansoft.liw. All rights reserved.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"
#import "BarCodeViewController.h"
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "BaseTabBarController.h"
#import "UserModel.h"
#import "CustomNavController.h"
#import "NoTUploadSendVC.h"
#import "NotUpdataTool.h"
@interface AppDelegate ()<UIAlertViewDelegate>
{
    BMKMapManager *_mapManager;
    BMKLocationService *_loaclService;
    BMKGeoCodeSearch *_geocodesearch;
    long Nsarraycount;
    NSInteger indexlong;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if ([[UserDefaults objectForKey:Indexlong]integerValue] ==0) {
        indexlong=1;

    }else{
        indexlong=[[UserDefaults objectForKey:Indexlong] integerValue];
    }
    
    [NSTimer scheduledTimerWithTimeInterval:43200 target:self selector:@selector(RefreshUserDate) userInfo:nil repeats:YES];
    
     [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status)
        {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
               
                if ([NotUpdataTool getImageArrayforSanbox:0].count!=0||[NotUpdataTool getUserdataArrayfprSanbox].count!=0) {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        //                    // 处理耗时操作的代码块...
                        Nsarraycount=[NotUpdataTool getImageArrayforSanbox:0].count;
                        [self setUploadViewControllerListCount:Nsarraycount];
                        
                    });}

                break;
            case 2:
                NSLog(@"wifi网络");
            if ([NotUpdataTool getImageArrayforSanbox:0].count!=0||[NotUpdataTool getUserdataArrayfprSanbox].count!=0) {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //                    // 处理耗时操作的代码块...
        
                [self uploaddatatosever];
                    
                });}
                break;
                
            default:
                break;
        }
    }];
    
// Override point for customization after application launch.
//    在这里面是实现登录跳转位置,
    if([UserDefaults boolForKey:KIsLogin]==YES){
        
        NSDictionary*Dict=[UserDefaults objectForKey:@"用户数据"];
        [[UserData shareUserData] saveUserInfoWith:Dict];

        NSLog(@"%@",[UserData shareUserData].userModel.dbId);
        
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取Main.storyboard中的第2个视图
        BaseTabBarController *BaseNav = [mainStory instantiateViewControllerWithIdentifier:@"BaseTabBarController"];
        //设置窗体的根视图为Storyboard里的视图
        self.window.rootViewController =BaseNav;
        
    }else{
        
        UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取Main.storyboard中的第2个视图
        LoginViewController *LoginNav = [mainStory instantiateViewControllerWithIdentifier:@"LoginNav"];
        self.window.rootViewController =LoginNav;

    }
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"f2IhMHQwjz8HFEcca9SMmL42GUidVuxU"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }else
    {
        NSLog(@"bmk start  success!");
    }

    
    [self setIQKeyBoard];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
 
    return YES;
}
//设置IQKeyBoard
-(void)setIQKeyBoard
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
   
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)setUploadViewControllerListCount:(long)ListCount{
    
    NSString*AleatStr=[NSString stringWithFormat:@"你有未上传寄件单%ld件,请上传？",ListCount];
    UIAlertView*Alleart=[[UIAlertView alloc]initWithTitle:@"邮寄精灵提示" message:AleatStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [Alleart show];
    
  
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex==0) {
        
        if (indexlong==2) {
            indexlong=0;
            [UserDefaults setInteger:indexlong forKey:Indexlong];

                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                 // 处理耗时操作的代码块...
            
                    [self uploaddatatosever];
                    
                });

            
        }else{
         indexlong++;
         [UserDefaults setInteger:indexlong forKey:Indexlong];
        }
     
       
    }else{
        if ([NotUpdataTool getImageArrayforSanbox:0].count!=0||[NotUpdataTool getUserdataArrayfprSanbox].count!=0) {

            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                // 处理耗时操作的代码块...

                [self uploaddatatosever];

            });


        }
    }
   
}
-(void)uploaddatatosever{
  //获取寄件单列表需要上传的数据
    @synchronized (self) {
        NSLog(@"使用异步函数执行主队列中的任务2--%@",[NSThread currentThread]);
        
        NSMutableArray*ImageArray=[NSMutableArray array];
        
        NSMutableArray*FistIIteamImage=[NotUpdataTool getImageArrayforSanbox:0];
        
        NSMutableArray*FistIOtherImage=[NotUpdataTool getImageArrayforSanbox:1];
        
        NSMutableArray*SendDataArray=[NSMutableArray arrayWithArray:[NotUpdataTool getUserDataforSanbox]];
        //完成寄件单列表上需要上传前数据的操作
        long Imageleng =FistIIteamImage.count;
        
        if (Imageleng>0) {
            
            NSDictionary*UploadDic=SendDataArray[0];
            NSString*recodID=UploadDic[@"recordid"];
            NotUpdataTool* NotUpdata=[NotUpdataTool new];
            
            if (FistIOtherImage.count!=0) {
                
                [ImageArray addObject:FistIIteamImage[0]];
                [ImageArray addObject:FistIOtherImage[0]];
                
                for (int i=0; i<ImageArray.count; i++) {
                    
                    [NotUpdata UploadImageForSevers:ImageArray[i] withtype:[NSString stringWithFormat:@"%d",i+1] RecondID:recodID withcycleCount:2 SuccessReturnBlock:^(NSDictionary *responseObject, int index) {
                        
                        if (index==1) {
                            
                        }else{
                            //清除图片
                            bool IsWriteYes=[NotUpdataTool removeImageforSanBox:1];
                            //清楚plist
                            if (IsWriteYes==YES) {
                                [NotUpdataTool removePolistForSanBox:0];
                            }
                            [SharedNotifiCenter postNotificationName:UPloadFinish object:nil];
                            //重新上传
                            [self uploaddatatosever];
                        }
                        
                    }];
                }
                
            }else{
                [NotUpdata UploadImageForSevers:FistIIteamImage[0] withtype:@"1" RecondID:recodID withcycleCount:1 SuccessReturnBlock:^(NSDictionary *responseObject, int index) {
                    if (index==1) {
                        //清除图片
                        bool IsWriteYes=[NotUpdataTool removeImageforSanBox:0];
                        //清楚plist
                        if (IsWriteYes==YES) {
                            [NotUpdataTool removePolistForSanBox:0];
                        }
                        [SharedNotifiCenter postNotificationName:UPloadFinish object:nil];
                        //重新上传
                        [self uploaddatatosever];
                    }
                    
                }];
            }
        }

    }
}

-(void)RefreshUserDate{
   
    NSMutableDictionary*Dict=[NSMutableDictionary dictionary];
    [Dict setObject:[UserData shareUserData].userModel.phone forKey:@"phone"];
   [[HttpAPI shareHttpAPI]getCheckUploadStaticForServers:Dict CallBack:^(NSDictionary *receivedData) {
       if ([receivedData[@"status"] integerValue]==1) {
           NSDictionary*userDict=receivedData[@"data"];
           NSString*uploadMode=userDict[@"uploadDataMode"];
           [UserDefaults setObject:uploadMode forKey:uploadDataModeStatic];
       }
   }];
}

@end
